﻿#region header

//  ***************************************************************************
// *                                LICENSE
//  ***************************************************************************
//  * "Haplous" .NET Simple 2D Game Framework
//  * 
//  * Copyright © Jonathan Evans 2014-2014
//  * 
//  * This program is free software; you can redistribute it and/or
//  * modify it under the terms of the GNU General Public License
//  * as published by the Free Software Foundation; either version 2
//  * of the License, or (at your option) any later version.
//  * 
//  * This program is distributed in the hope that it will be useful,
//  * but WITHOUT ANY WARRANTY; without even the implied warranty of
//  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  * GNU General Public License for more details.
//  * 
//  * You should have received a copy of the GNU General Public License
//  * along with this program; if not, write to the Free Software
//  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//  * 
//  ***************************************************************************
//  * 
//  * Contact: opencollar@googlemail.com
//  * 
//  * Website: http://haplous.codeplex.com/
//  *
//  * NuGet:   http://www.nuget.org/packages/haplous/
//  *
//  * File:    Haplous/Haplous/PictureSource.cs
//  *
//  ***************************************************************************

#endregion

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Threading;

using Haplous.Core;

using JetBrains.Annotations;

namespace Haplous
{
    /// <summary>
    ///     A class representing the source of a picture or sequence of pictures.
    /// </summary>
    [DebuggerDisplay("PictureSource: Name={_source.Name}")]
    public sealed class PictureSource : DisposableNotifyObject, IProperty<PictureSource>
    {
        /// <summary>
        ///     The lock used to control concurrent access to the <see cref="_source" /> field.
        /// </summary>
        [NotNull]
        private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

        /// <summary>
        ///     The picture source that will act as a provider.
        /// </summary>
        /// <remarks>Concurrent access is controlled by the <see cref="_lock" /> field.</remarks>
        [CanBeNull]
        private IPicture _source;

        /// <summary>
        ///     The picture source that will act as a provider.
        /// </summary>
        [CanBeNull]
        public IPicture Source
        {
            get { return _source; }
            set
            {
                var oldPicture = _source;
                if(OnPropertyChanged("Source", ref _source, value, _lock))
                {
                    // Hook event handler to the new source.
                    if(value != null)
                        value.PropertyChanged += PictureChanged;

                    // Unhook the event handlers from the old source.
                    if(oldPicture != null)
                        oldPicture.PropertyChanged -= PictureChanged;

                    OnPictureChanged();
                }
            }
        }

        /// <summary>
        ///     Gets the current active image.
        /// </summary>
        /// <value>The active image (which may be <see langword="null" />).</value>
        [CanBeNull]
        public Image ActiveImage
        {
            get
            {
                if(_source != null)
                    return _source.ActiveImage;

                return null;
            }
        }

        /// <summary>
        ///     Copies the value of the specified property object into the current property object.
        /// </summary>
        /// <param name="property">The property object from which to copy the value.</param>
        public void Copy(IProperty<PictureSource> property)
        {
            Source = ((PictureSource)property).Source;
        }

        /// <summary>
        ///     Called when active picture changes.
        /// </summary>
        private void OnPictureChanged()
        {
            OnPropertyChanged("ActiveImage");
        }

        /// <summary>
        ///     Called when a property on the active picture source changes.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="PropertyChangedEventArgs" /> instance containing the event data.</param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void PictureChanged([CanBeNull] object sender, [NotNull] PropertyChangedEventArgs e)
        {
            try
            {
                if(e.PropertyName != "ActiveImage")
                    return;

                OnPictureChanged();
            }
            catch(Exception ex)
            {
                ErrorManager.OnUnhandledException(ex);
            }
        }
    }
}